<?php

declare(strict_types=1);
/**
 * This file is part of Hyperf.
 *
 * @link     https://www.hyperf.io
 * @document https://hyperf.wiki
 * @contact  group@hyperf.io
 * @license  https://github.com/hyperf/hyperf/blob/master/LICENSE
 */

namespace App\Exception\Handler;

use App\Model\UserActionsLog;
use Hyperf\Context\Context;
use Hyperf\ExceptionHandler\ExceptionHandler;
use Hyperf\HttpMessage\Stream\SwooleStream;
use Hyperf\Validation\ValidationException;
use Swow\Psr7\Message\ResponsePlusInterface;
use Throwable;
use function Hyperf\Translation\trans;

class AppValidationExceptionHandler extends ExceptionHandler
{
    public function handle(Throwable $throwable, ResponsePlusInterface $response)
    {
        $this->stopPropagation();
        /** @var ValidationException $throwable */
        $body = $throwable->validator->errors()->first();
        // $body1 = json_decode(json_encode($body),true);
        // $messageKeys = array_keys($body1);
        // $message = trans('validation.'.$messageKeys[0],['attribute' => $body1[$messageKeys[0]][0]],'zh-hk');
        // $language = Context::get('language');

        $data = json_encode(['code' => $throwable->status, 'message' => $body, 'data' => []], JSON_UNESCAPED_UNICODE);
        if (!$response->hasHeader('content-type')) {
            $response = $response->addHeader('content-type', 'application/json;charset=utf-8');
        }
        $apiLogId = Context::get('apiLogId');
        UserActionsLog::query()->where('id', $apiLogId)->update(['response' => $data]);
        return $response->setStatus(200)->setBody(new SwooleStream($data));
    }

    public function isValid(Throwable $throwable): bool
    {
        return $throwable instanceof ValidationException;
    }
}
